var type = window.PERSISTENT; // || window.TEMPORARY
var size = 1 * 1024 * 1024 * 1024;
var file = null;
navigator.StorageQuota = null;
if (type == window.TEMPORARY) {
    navigator.StorageQuota = navigator.webkitTemporaryStorage;
} else {
    navigator.StorageQuota = navigator.webkitPersistentStorage;
}
window.requestFileSystem = window.webkitRequestFileSystem || window.requestFileSystem;
navigator.StorageQuota.requestQuota(size, function(space) {
    window.requestFileSystem(type, space, function(fileSystem) {
        file = fileSystem;
        // file.root.getFile('index.html', {create:true});
        explorer(file.root);
    });
});
function newFolder(root, folder) {
    return root.getDirectory(folder[0], {create:true}, function(info) {
        if (folder.length) {
            newFolder(info, folder.slice(1));
        };
        explorer(root);

    });
}
function newFolderName(name) {
    return name.split('/');
}
$('#newFolder').linkbutton({
    onClick: function(info) {
        $.messager.prompt('New Folder', 'What name of your new folder ?', function(infoPrompt) {
            file.root.getDirectory(infoPrompt, {create:true}, function(infoGetFile) {
                console.log(infoGetFile);
                explorer(file.root);
                alert('Folder with name '+ infoPrompt+ ' has ben created.');
            });
        });
    }
});
$('#newMultipleFolder').linkbutton({
    onClick: function(info) {
        $.messager.prompt('New Folder', 'What name of your new folder ?', function(infoPrompt) {
            newFolder(file.root, newFolderName(infoPrompt));
        });
    }
});
function explorer(root) {
    var reader = root.createReader();
    reader.readEntries(function(entries) {
        var ff = new Array(); 
        for(var i = 0, e; e = entries[i]; i++) {
            ff.push('<a href="javascript:void(0)" path="'+e.fullPath+'" style="display:block;">'+e.name+'</a>');
        }
        $('#explorer').empty().html(ff.join(''));
    });
}

$(document).bind("click", function(e) {
    var text = $(e.target).attr('path');
    file.root.getDirectory(text, {}, function(info) {
        explorer(info);
    });
});

$('#file').bind('change', function(e) {
    file.root.getFile(e.target.files[0].name, {create: true}, function(fileEntry) {
        fileEntry.createWriter(function(writer) {
            writer.onwrite = function(e) {};
            writer.onerror = function(e) {};
            var blob = new Blob([e.target.files[0]], {type: e.target.files[0].type});
            writer.write(blob);
            explorer(file.root);
        });
    });
});